<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>认识图形</title>
    <!-- KaTeX CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css">
    <!-- KaTeX JS -->
    <script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js"></script>
    <!-- KaTeX Auto-render Extension -->
    <script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/contrib/auto-render.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <style>
        :root {
            --point-color: #FF6B6B;
            --line-color: #4D96FF;
            --surface-color: #6BCB77;
            --solid-color: #B088F9;
            --bg-gradient: linear-gradient(135deg, #f6f8ff 0%, #f1f1f9 100%);
            --panel-bg: #ffffff;
            --border-color: #e5e7eb;
            --text-primary: #1f2937;
            --text-secondary: #4b5563;
        }

        body {
            margin: 0;
            padding: 20px;
            min-height: 100vh;
            font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
            background: var(--bg-gradient);
            color: var(--text-primary);
        }

        /* 主容器样式优化 */
        .main-wrapper {
            display: flex;
            min-height: 700px;
            max-width: 1600px;
            margin: 0 auto 30px;
            background: var(--panel-bg);
            border-radius: 16px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            overflow: hidden;
        }

        /* 左侧面板优化 */
        .left-panel {
            flex: 0 0 320px;
            border-right: 1px solid var(--border-color);
            background: #fafafa;
            padding: 24px 0;
            overflow-y: auto;
        }

        .left-panel h1 {
            font-size: 20px;
            color: var(--text-primary);
            margin: 0 24px 24px;
            padding-bottom: 16px;
            border-bottom: 1px solid var(--border-color);
        }

        /* 中间面板优化 */
        .center-panel {
            flex: 0 0 560px;
            border-right: 1px solid var(--border-color);
            padding: 24px;
            display: flex;
            flex-direction: column;
        }

        /* 右侧面板优化 */
        .right-panel {
            flex: 1;
            padding: 24px;
            background: #fff;
        }

        /* 折叠面板样式优化 */
        .accordion-item {
            border: none;
            background: transparent;
        }

        .accordion-button {
            padding: 12px 24px;
            font-size: 15px;
            font-weight: 500;
            color: var(--text-primary);
            background: transparent;
        }

        .accordion-button:not(.collapsed) {
            background: transparent;
            color: var(--text-primary);
        }

        .accordion-button::before {
            content: '▸';
            margin-right: 12px;
            font-size: 16px;
            transition: transform 0.2s;
        }

        .accordion-button:not(.collapsed)::before {
            transform: rotate(90deg);
        }

        /* 子分类样式优化 */
        .sub-category {
            padding: 10px 24px 10px 48px;
            font-size: 14px;
            color: var(--text-secondary);
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .sub-category:hover {
            background: rgba(0, 0, 0, 0.03);
            color: var(--text-primary);
        }

        .sub-category.active {
            background: rgba(0, 0, 0, 0.05);
            color: var(--text-primary);
            font-weight: 500;
        }

        /* 画布容器优化 */
        .canvas-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            background: #fafafa;
            border-radius: 12px;
            padding: 20px;
        }

        .canvas-title {
            font-size: 18px;
            color: var(--text-primary);
            margin-bottom: 20px;
            text-align: center;
        }

        .geometry-canvas {
            width: 500px !important;
            height: 500px !important;
            background: #fff;
            border-radius: 8px;
            border: 1px solid var(--border-color);
            margin: 0 auto;
        }

        /* 内容区域优化 */
        .content-area {
            height: 100%;
        }

        .content-title {
            font-size: 20px;
            color: var(--text-primary);
            margin-bottom: 24px;
            padding-bottom: 16px;
            border-bottom: 1px solid var(--border-color);
        }

        .content-description {
            color: var(--text-secondary);
            line-height: 1.8;
            font-size: 15px;
        }

        .content-description h3 {
            color: var(--text-primary);
            font-size: 16px;
            margin: 24px 0 12px;
        }

        .content-description ul {
            padding-left: 20px;
            margin: 12px 0;
        }

        .content-description li {
            margin: 8px 0;
        }

        /* 欢迎页面优化 */
        .welcome-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            color: var(--text-secondary);
            background: #fafafa;
            border-radius: 12px;
            padding: 40px;
        }

        .welcome-content h2 {
            color: var(--text-primary);
            margin-bottom: 16px;
        }

        /* 练习区域优化 */
        .practice-container {
            max-width: 1600px;
            margin: 0 auto 40px;
            background: var(--panel-bg);
            border-radius: 16px;
            padding: 24px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
        }

        .practice-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 24px;
            padding-bottom: 16px;
            border-bottom: 1px solid var(--border-color);
        }

        .practice-header h2 {
            font-size: 20px;
            color: var(--text-primary);
            margin: 0;
        }

        .btn-generate {
            padding: 8px 20px;
            border: none;
            border-radius: 6px;
            background: var(--line-color);
            color: white;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.2s;
        }

        .btn-generate:hover {
            background: #3d85ff;
        }

        /* 题目区域样式 */
        .question-item {
            background: #fff;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
        }

        .question-title {
            font-size: 16px;
            color: var(--text-primary);
            margin-bottom: 16px;
            line-height: 1.6;
        }

        .options-list {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 12px;
        }

        .option-item {
            margin: 0;
        }

        .option-item label {
            display: flex;
            align-items: center;
            padding: 12px;
            border: 1px solid var(--border-color);
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.2s;
        }

        .option-item label:hover {
            background: rgba(77, 150, 255, 0.05);
        }

        .option-item input[type="radio"] {
            margin-right: 10px;
        }

        .option-item input[type="radio"]:checked + span {
            color: var(--line-color);
            font-weight: 500;
        }

        /* 提交按钮容器 */
        .submit-container {
            display: flex;
            justify-content: center;
            margin-top: 30px;
        }

        /* 结果区域样式 */
        .result-area {
            margin-top: 30px;
            padding: 24px;
            background: #f8f9fa;
            border-radius: 8px;
        }

        .score {
            font-size: 28px;
            color: var(--line-color);
            text-align: center;
            margin-bottom: 20px;
            font-weight: bold;
        }

        .feedback {
            color: var(--text-secondary);
            line-height: 1.8;
        }

        /* 加载状态 */
        .loading {
            text-align: center;
            padding: 40px;
            color: var(--text-secondary);
            font-size: 16px;
        }

        .loading::after {
            content: '...';
            animation: dots 1.5s steps(4, end) infinite;
        }

        @keyframes dots {
            0%, 20% { content: '.'; }
            40% { content: '..'; }
            60% { content: '...'; }
            80%, 100% { content: ''; }
        }

        /* 欢迎练习区域 */
        .welcome-practice {
            text-align: center;
            padding: 40px;
            color: var(--text-secondary);
        }

        /* 错误提示 */
        .error {
            color: #dc3545;
            text-align: center;
            padding: 20px;
        }
    </style>
</head>
<body>
    <div class="main-wrapper">
        <div class="left-panel">
            <h1>图形的分类体系</h1>
            <div class="geometry-categories accordion" id="geometryAccordion">
                <!-- 点 -->
                <div class="accordion-item">
                    <h2 class="accordion-header" id="pointHeading">
                        <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#pointCollapse">
                            点 Point
                        </button>
                    </h2>
                    <div id="pointCollapse" class="accordion-collapse collapse show" data-bs-parent="#geometryAccordion">
                        <div class="accordion-body">
                            <div class="sub-category" data-type="point-basic">基本概念</div>
                            <div class="sub-category" data-type="point-coordinate">坐标平面中的点</div>
                        </div>
                    </div>
                </div>

                <!-- 线 -->
                <div class="accordion-item">
                    <h2 class="accordion-header" id="lineHeading">
                        <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#lineCollapse">
                            线 Line
                        </button>
                    </h2>
                    <div id="lineCollapse" class="accordion-collapse collapse" data-bs-parent="#geometryAccordion">
                        <div class="accordion-body">
                            <div class="sub-category" data-type="line-straight">直线</div>
                            <div class="sub-category" data-type="line-segment">线段</div>
                            <div class="sub-category" data-type="line-ray">射线</div>
                        </div>
                    </div>
                </div>

                <!-- 面 -->
                <div class="accordion-item">
                    <h2 class="accordion-header" id="surfaceHeading">
                        <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#surfaceCollapse">
                            面 Surface
                        </button>
                    </h2>
                    <div id="surfaceCollapse" class="accordion-collapse collapse" data-bs-parent="#geometryAccordion">
                        <div class="accordion-body">
                            <div class="sub-category" data-type="surface-angle">角</div>
                            <div class="sub-category" data-type="surface-triangle">三角形</div>
                            <div class="sub-category" data-type="surface-quadrilateral">四边形</div>
                            <div class="sub-category" data-type="surface-polygon">多边形</div>
                            <div class="sub-category" data-type="surface-circle">圆</div>
                            <div class="sub-category" data-type="surface-arc">弧和扇形</div>
                        </div>
                    </div>
                </div>

                <!-- 体 -->
                <div class="accordion-item">
                    <h2 class="accordion-header" id="solidHeading">
                        <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#solidCollapse">
                            体 Solid
                        </button>
                    </h2>
                    <div id="solidCollapse" class="accordion-collapse collapse" data-bs-parent="#geometryAccordion">
                        <div class="accordion-body">
                            <div class="sub-category" data-type="solid-cube">立方体</div>
                            <div class="sub-category" data-type="solid-cuboid">长方体</div>
                            <div class="sub-category" data-type="solid-sphere">球体</div>
                            <div class="sub-category" data-type="solid-cone">圆锥</div>
                            <div class="sub-category" data-type="solid-prism">棱柱</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="center-panel">
            <div id="welcome" class="welcome-content">
                <h2>欢迎学习几何图形</h2>
                <p>点击左侧分类开始学习</p>
            </div>
            <div id="canvas-container" class="canvas-container" style="display: none;">
                <h3 id="canvas-title" class="canvas-title"></h3>
                <canvas id="geometry-canvas" class="geometry-canvas"></canvas>
            </div>
        </div>
        <div class="right-panel">
            <div id="content" class="content-area" style="display: none;">
                <h3 id="content-title" class="content-title"></h3>
                <div id="content-description" class="content-description"></div>
            </div>
        </div>
    </div>

    <!-- 练习区域 -->
    <div class="practice-container">
        <div class="practice-header">
            <h2>练习题</h2>
            <button class="btn-generate" id="generateQuestions">生成新题目</button>
        </div>
        <div class="practice-content" id="practiceContent">
            <div class="welcome-practice" id="welcomePractice">
                <p>点击"生成新题目"开始练习</p>
            </div>
            <div class="questions-area" id="questionsArea" style="display: none;"></div>
            <div class="result-area" id="resultArea" style="display: none;"></div>
        </div>
    </div>

    <script type="module">
        import geometryTypes from '/plugins/geometry_learning/assets/js/geometry-data.js';
        
        document.querySelectorAll('.sub-category').forEach(subCategory => {
            subCategory.addEventListener('click', () => {
                // 移除其他活动状态
                document.querySelectorAll('.sub-category').forEach(c => c.classList.remove('active'));
                subCategory.classList.add('active');

                const type = subCategory.dataset.type;
                const info = geometryTypes[type];
                
                // 隐藏欢迎信息
                document.getElementById('welcome').style.display = 'none';
                
                // 显示内容区域
                document.getElementById('content').style.display = 'block';
                document.getElementById('canvas-container').style.display = 'block';
                
                // 更新内容
                document.getElementById('content-title').textContent = info.title;
                document.getElementById('canvas-title').textContent = info.title;
                document.getElementById('content-description').innerHTML = marked.parse(info.description);
                
                // 获取画布并设置尺寸
                const canvas = document.getElementById('geometry-canvas');
                
                // 调用绘图函数
                if (typeof info.drawDemo === 'function') {
                    info.drawDemo(canvas);
                }
            });
        });

        // 添加练习相关的代码
        const generateQuestions = async () => {
            const questionsArea = document.getElementById('questionsArea');
            const welcomePractice = document.getElementById('welcomePractice');
            const resultArea = document.getElementById('resultArea');
            const generateBtn = document.getElementById('generateQuestions');

            // 显示加载状态
            welcomePractice.style.display = 'none';
            resultArea.style.display = 'none';
            questionsArea.style.display = 'block';
            questionsArea.innerHTML = '<div class="loading">正在生成题目</div>';
            generateBtn.disabled = true;

            try {
                // 获取当前选中的几何类型
                const activeCategory = document.querySelector('.sub-category.active');
                if (!activeCategory) {
                    alert('请先选择一个几何图形类型');
                    generateBtn.disabled = false;
                    return;
                }

                const type = activeCategory.dataset.type;
                const info = geometryTypes[type];
                
                const prompt = `请生成5道关于${info.title}的选择题，包括2个概念认识题、2个计算题和1个应用题。

知识范围：
${info.description.replace(/\n/g, ' ')}

要求：
1. 每道题必须有4个选项(A、B、C、D)
2. 必须包含正确答案
3. 难度适中
4. 题目必须紧密结合${info.title}的特点和性质
5. 可以使用 LaTeX 数学公式，用 \\( \\) 包裹行内公式，用 \\[ \\] 包裹独立公式
6. 概念题应该考察${info.title}的定义和性质
7. 计算题应该涉及${info.title}的相关计算
8. 应用题要体现${info.title}在实际中的应用

返回格式：
## 题目
1. [第1题]
   A. [选项A]
   B. [选项B]
   C. [选项C]
   D. [选项D]

... (其他题目)

## 答案
1. [答案]
...

## 解析
1. [解析]
...`;

                const response = await fetch('/api/ai/chat', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        messages: [{
                            role: 'user',
                            content: prompt
                        }],
                        stream: true
                    })
                });

                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let markdown = '';

                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;

                    const chunk = decoder.decode(value);
                    const lines = chunk.split('\n');

                    for (const line of lines) {
                        if (line.startsWith('data: ')) {
                            try {
                                const data = JSON.parse(line.slice(5));
                                if (data.content) {
                                    markdown += data.content;
                                    // 实时更新显示
                                    const formattedContent = parseMarkdown(markdown);
                                    questionsArea.innerHTML = formattedContent;
                                    // 修改滚动逻辑
                                    window.scrollTo({
                                        top: document.documentElement.scrollHeight,
                                        behavior: 'smooth'
                                    });
                                }
                            } catch (e) {
                                console.error('Error parsing JSON:', e);
                            }
                        }
                    }
                }

                // 添加提交按钮
                const submitContainer = document.createElement('div');
                submitContainer.className = 'submit-container';
                
                const submitBtn = document.createElement('button');
                submitBtn.className = 'btn-generate';
                submitBtn.textContent = '提交答案';
                
                submitContainer.appendChild(submitBtn);
                questionsArea.appendChild(submitContainer);

                submitBtn.addEventListener('click', () => {
                    const selectedAnswers = [];
                    const questionElements = questionsArea.querySelectorAll('.question-item');
                    questionElements.forEach((question, index) => {
                        const selected = question.querySelector('input[type="radio"]:checked');
                        selectedAnswers.push(selected ? selected.value : null);
                    });

                    // 解析答案和计算分数
                    const correctAnswers = markdown.match(/## 答案\n([\s\S]*?)(?=\n## |$)/)[1]
                        .split('\n')
                        .filter(line => line.trim())
                        .map(line => line.replace(/^\d+\.\s*/, '').trim());

                    const explanationsText = markdown.match(/## 解析\n([\s\S]*?)(?=\n## |$)/)[1]
                        .split('\n')
                        .filter(line => line.trim())
                        .map(line => line.replace(/^\d+\.\s*/, '').trim());

                    let score = 0;
                    const feedback = selectedAnswers.map((answer, index) => {
                        const isCorrect = answer === correctAnswers[index];
                        if (isCorrect) score += 20;
                        return `第${index + 1}题: ${isCorrect ? '✓' : '✗'}\n解析: ${explanationsText[index]}`;
                    });

                    // 显示结果
                    resultArea.style.display = 'block';
                    resultArea.innerHTML = `
                        <div class="score">得分：${score}</div>
                        <div class="feedback">${feedback.join('\n\n').replace(/\n/g, '<br>')}</div>
                    `;

                    // 渲染结果区域中的数学公式
                    renderMathInElement(resultArea, {
                        delimiters: [
                            {left: "\\(", right: "\\)", display: false},
                            {left: "\\[", right: "\\]", display: true},
                            {left: "$", right: "$", display: false},
                            {left: "$$", right: "$$", display: true}
                        ],
                        throwOnError: false
                    });

                    // 修改结果显示后的滚动逻辑
                    setTimeout(() => {
                        resultArea.scrollIntoView({ 
                            behavior: 'smooth', 
                            block: 'center'
                        });
                    }, 100);
                });

            } catch (error) {
                questionsArea.innerHTML = `<div class="error">生成题目时出错：${error.message}</div>`;
            } finally {
                generateBtn.disabled = false;
            }
        };

        function parseMarkdown(markdown) {
            // 提取题目部分
            const questionsMatch = markdown.match(/## 题目\n([\s\S]*?)(?=\n## |$)/);
            if (!questionsMatch) return markdown;

            const questionsText = questionsMatch[1];
            const questions = questionsText.split('\n\n').filter(q => q.trim());

            const html = questions.map((question, index) => {
                const lines = question.split('\n').filter(line => line.trim());
                const title = lines[0].replace(/^\d+\.\s*/, '');
                const options = lines.slice(1).map(line => {
                    const [label, ...text] = line.trim().split('. ');
                    return {
                        label,
                        text: text.join('. ')
                    };
                });

                return `
                    <div class="question-item">
                        <div class="question-title">${index + 1}. ${title}</div>
                        <div class="options-list">
                            ${options.map(option => `
                                <div class="option-item">
                                    <label>
                                        <input type="radio" name="question${index}" value="${option.label}">
                                        <span>${option.label}. ${option.text}</span>
                                    </label>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                `;
            }).join('');

            const container = document.createElement('div');
            container.innerHTML = html;

            // 渲染数学公式
            renderMathInElement(container, {
                delimiters: [
                    {left: "\\(", right: "\\)", display: false},
                    {left: "\\[", right: "\\]", display: true},
                    {left: "$", right: "$", display: false},
                    {left: "$$", right: "$$", display: true}
                ],
                throwOnError: false
            });

            return container.innerHTML;
        }

        // 添加生成题目按钮的点击事件监听器
        document.getElementById('generateQuestions').addEventListener('click', () => {
            const activeCategory = document.querySelector('.sub-category.active');
            if (!activeCategory) {
                alert('请先选择一个几何图形类型再生成题目');
                return;
            }
            generateQuestions();
        });
    </script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html> 